package org.example.day12;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 *  5.1.2.4 TimerTask类中的cancel方法.
 *      作用: 将自身从任务队列中清除
 *      debug测试一下: 执行cancel后只是将task的state标志位从1改到3.真正移除queue是在mainLoop方法中: if (task.state == TimerTask.CANCELLED) {queue.removeMin()}
 */
public class MyThread11 {
    static public class MyTaskA extends TimerTask{
        @Override
        public void run() {
            System.out.println("A运行了！ 时间为: " + new Date());
            this.cancel();
        }
    }
    static public class MyTaskB extends TimerTask{
        @Override
        public void run() {
            System.out.println("B运行了！ 时间为: " + new Date());
        }
    }

    public static void main(String[] args) {
        try {
            MyTaskA taskA = new MyTaskA();
            MyTaskB taskB = new MyTaskB();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString1 = "2022-05-16 11:09:00";
            Timer timer = new Timer();
            Date dateRef = sdf.parse(dateString1);
            System.out.println("字符串时间为: " + dateRef.toLocaleString() + " 当前时间: " + new Date().toLocaleString());
            timer.schedule(taskA,dateRef,4000);
            timer.schedule(taskB,dateRef,4000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
